package com.hth.service;

import java.net.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.*;

import com.hth.data.DataObject;
import com.hth.main.Main;

public class GreetingServer extends Thread {
	
	public static final int TYPE_INSERT = 1;
	public static final int TYPE_QUERY = 2;
	private ServerSocket serverSocket;

	public GreetingServer(int port) throws IOException {
		serverSocket = new ServerSocket(port);
//		serverSocket.setSoTimeout(20000);
	}

	public void run() {
		while (true) {
			try {
				System.out.println("Lắng nghe client trên cổng: " + serverSocket.getLocalPort() + "...");
				Socket server = serverSocket.accept();
				System.out.println("Just connected to " + server.getRemoteSocketAddress());
				
				DataInputStream dataInputStream = new DataInputStream(server.getInputStream());
				String data = dataInputStream.readUTF();
				System.out.println("data: " + data);
				
				DataOutputStream dataOutputStream = new DataOutputStream(server.getOutputStream());
				dataOutputStream.writeUTF(processData(data));
				
				server.close();
			} catch (SocketTimeoutException s) {
				System.out.println("Socket timed out!");
				break;
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
		}
	}
	
	private String processData(String data) {
		switch (getTypeData(data)) {
		case TYPE_INSERT:
			return insertData(data);
		case TYPE_QUERY:
			return getData(data);
		default:
			return "Toi khong hieu";
		}
	}
	
	private int getTypeData(String data) {
		String arrayString[] = data.split("-");
		if (arrayString[0].equals("insert")) {
			return TYPE_INSERT;
		} else {
			return TYPE_QUERY;
		}
	}
	
	private String getData(String id) {
		String resultString = "Khong thay du lieu!!!";
		try {
			String sql = "SELECT * FROM localtable WHERE id=\'" + id + "\'";
			ResultSet resultSet = Main.MYSQL_MANAGER.executeQuery(sql);
			// STEP 5: Extract data from result set
			while (resultSet.next()) {
				String idResult = resultSet.getString("id");
				double xPosition = resultSet.getInt("x_position");
				double yPosition = resultSet.getInt("y_position");

				resultString = idResult + " - " + xPosition + " - " + yPosition;
			}
			// STEP 6: Clean-up environment
			resultSet.close();
		} catch (SQLException se) {
			se.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return resultString;
	}
	
	private String insertData(String data) {
		DataObject dataObject = new DataObject(data);
		String sql = "INSERT INTO localtable (id, x_position, y_position) " +
				"VALUES ('" + dataObject.getId() + "', " + dataObject.getxPosition() 
				+ ", " + dataObject.getyPosition() + ")";
		Main.MYSQL_MANAGER.executeUpdate(sql);
		return "Da insert id" + dataObject.getId();
	}
}